﻿<template>
    <el-table :data="mediaList" disabled :show-header="false" size="mini" style="width:100%;" :empty-text="emptyText">
        <el-table-column class-name="v-top">
            <template #default="d">
                <div class="bg-white">
                    <el-input v-if="d.row.miType==1" type="textarea" placeholder="请输入内容" v-model="d.row.miTitle" maxlength="1000" show-word-limit :autosize="{minRows:3}" resize="none" :readonly="disabled"></el-input>
                    <template v-else-if="d.row.miType==2">
                        <el-avatar shape="square" :size="120" class="bg-light margin-right-20" style="position:relative; margin:10px 20px 0 10px;">
                            <el-image :src="d.row.miUrl" fit="cover" class="h100 w100 hidden" :preview-src-list="[d.row.miUrl]" lazy></el-image>
                        </el-avatar>
                    </template>
                    <template v-else-if="d.row.miType==3">
                        <audio :src="!!d.row.rawUrl?d.row.rawUrl:d.row.miUrl" controls style="margin: 10px 20px 0 10px;">您的浏览器不支持音频播放</audio>
                    </template>
                    <template v-else-if="d.row.miType==4">
                        <el-avatar shape="square" :size="120" class="bg-light margin-right-20" style="position:relative; margin:10px 20px 0 10px; width:auto;">
                            <video :src="!!d.row.rawUrl?d.row.rawUrl:d.row.miUrl" style="height:auto; max-height:120px;" controls>您的浏览器不支持视频播放</video>
                        </el-avatar>
                    </template>
                    <template v-else-if="d.row.miType==5">
                        <el-input placeholder="请输入链接描述" v-model="d.row.miTitle" style="margin-bottom:5px;" resize="none" :readonly="disabled"></el-input>
                        <el-input placeholder="请输入链接" v-model="d.row.miUrl" resize="none" :readonly="disabled"></el-input>
                    </template>
                    <template v-else-if="d.row.miType==7">
                        <div class="flex-row" style="margin: 10px 20px 0 10px; padding:4px 0;">
                            <div style="padding:0 8px 0 4px;">
                                <i :class="[getFileIco(d.row.miTitle),'color-999']" style="font-size:2.5em !important;"></i>
                            </div>
                            <div class="flex-row-fill" style="line-height:20px !important;">
                                <div class="color-333">{{d.row.miTitle}}</div>
                                <div class="color-666">{{d.row.miSize}}</div>
                            </div>
                        </div>
                    </template>
                </div>
            </template>
        </el-table-column>
        <el-table-column width="150px" class-name="v-top">
            <template #default="d">
                <div>
                    <el-button :disabled="d.$index==0||disabled" type="text" icon="fa fa-arrow-up fa-fw" v-on:click="moveMedia(0,d.row,d.$index)">上移</el-button>
                    <el-button type="text" :disabled="d.$index==mediaList.length-1||disabled" icon="fa fa-arrow-down fa-fw" v-on:click="moveMedia(1,d.row,d.$index)">下移</el-button>
                    <br />
                    <el-button type="text" :disabled="disabled" icon="fa fa-close fa-fw" v-on:click="moveMedia(2,d.row,d.$index)">删除</el-button>
                    <el-dropdown trigger="click" :disabled="disabled" v-on:command="addMedia" class="margin-left-10">
                        <el-button type="text" icon="fa fa-dedent fa-fw">插入</el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :command="{type:1,item:d.row,index:d.$index}" v-if="fn.text">
                                <i class="fa fa-file-text-o"></i>文字
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <file-cover v-on:change="selectFile($event,{type:2,item:d.row,index:d.$index})" :accept="getFileType(2,1)"  v-if="fn.image">
                                    <i class="fa fa-file-image-o"></i>
                                    <span>图片</span>
                                </file-cover>
                            </el-dropdown-item>
                            <el-dropdown-item v-if="fn.audio">
                                <file-cover v-on:change="selectFile($event,{type:3,item:d.row,index:d.$index})" :accept="getFileType(3,1)">
                                    <i class="fa fa-file-audio-o"></i>
                                    <span>音频</span>
                                </file-cover>
                            </el-dropdown-item>
                            <el-dropdown-item v-if="fn.video">
                                <file-cover v-on:change="selectFile($event,{type:4,item:d.row,index:d.$index})" :accept="getFileType(4,1)">
                                    <i class="fa fa-file-video-o"></i>
                                    <span>视频</span>
                                </file-cover>
                            </el-dropdown-item>
                            <el-dropdown-item v-if="fn.file">
                                <file-cover v-on:change="selectFile($event,{type:7,item:d.row,index:d.$index})" :accept="getFileType(7,1)">
                                    <i class="fa fa-file-pdf-o"></i>
                                    <span>文件</span>
                                </file-cover>
                            </el-dropdown-item>
                            <el-dropdown-item :command="{type:5,item:d.row,index:d.$index}" v-if="fn.share">
                                <i class="fa fa-share-alt"></i>链接
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </template>
        </el-table-column>
        <template #append>
            <div class="bg-light padding-left-10">
                <el-button type="text" icon="fa fa-file-text-o" :disabled="disabled" v-on:click="addMedia({type:1})" v-if="fn.text">文字</el-button>
                @*<el-button type="text" icon="fa fa-file-text-o" v-on:click="addMedia({type:2})">图片</el-button>*@
                <el-dropdown trigger="click" class="margin-left-10" v-on:command="ClipBoard" :disabled="disabled" v-if="fn.image">
                    <el-button type="text" icon="fa fa-file-image-o">图片</el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="{type:2}">
                            <i class="fa fa-file-text-o"></i>从剪切板导入
                        </el-dropdown-item>
                        <el-dropdown-item>
                            <file-cover v-on:change="selectFile($event,{type:2})" :accept="getFileType(2,1)">
                                <i class="fa fa-file-image-o"></i>
                                <span>从文件选择</span>
                            </file-cover>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                @*<el-button type="text">
                        <file-cover v-on:change="selectFile($event,{type:2})" :accept="getFileType(2,1)">
                            <i class="fa fa-file-image-o"></i>
                            <span>图片</span>
                        </file-cover>
                    </el-button>*@
                <el-button type="text" class="margin-left-10" :disabled="disabled" v-if="fn.audio">
                    <file-cover v-on:change="selectFile($event,{type:3})" :accept="getFileType(3,1)">
                        <i class="fa fa-file-audio-o"></i>
                        <span>音频</span>
                    </file-cover>
                </el-button>
                <el-button type="text" :disabled="disabled" v-if="fn.video">
                    <file-cover v-on:change="selectFile($event,{type:4})" :accept="getFileType(4,1)">
                        <i class="fa fa-file-video-o"></i>
                        <span>视频</span>
                    </file-cover>
                </el-button>
                <el-button type="text" :disabled="disabled" v-if="fn.file">
                    <file-cover v-on:change="selectFile($event,{type:7})" :accept="getFileType(7,1)">
                        <i class="fa fa-file-pdf-o"></i>
                        <span>文件</span>
                    </file-cover>
                </el-button>
                <el-button type="text" icon="fa fa-share-alt" v-on:click="addMedia({type:5})" :disabled="disabled" v-if="fn.share">链接</el-button>
            </div>
        </template>
        <el-dialog :append-to-body="true" title="剪切板导入图片" :close-on-click-modal="false"
                   :visible.sync="showImgIpt" top="25vh" custom-class="el-dialog-custom"
                   width="400px"
                   center>
            <el-input id="input" v-model="ImgIptTxt" ref="ImgIpt" maxlength="0" clearable placeholder="请按键盘【Ctrl+V】粘贴图片" v-on:paste.native="handlePaste"></el-input>
        </el-dialog>
    </el-table>
</template>
<script>
    module = (function (hxt) {
        return {
            props: {
                value: {
                    type: Object,
                    default: {}
                },
                fn: {
                    type: Object,
                    default: {
                        audio: true,
                        video: true,
                        file: true,
                        share: true,
                        text: true,
                        image:true
                    }
                },
                emptyText: {
                    type: String,
                    default: "请添加文档内容"
                },
                disabled: {
                    type: Boolean,
                    default: false
                }
            },
            data: function () {
                return {
                    showImgIpt: false,
                    ImgIptTxt: ''
                };
            },
            computed: {
                mediaList: {
                    get: function () {
                        var v = this.value;
                        if (!hxt.isArray(v)) v = [];
                        return v;
                    },
                    set: function (val) {
                        this.$emit('input', val);
                    }
                }
            },
            methods: {
                // 按下按键
                //keyDown: function () {
                //    var _this = this;
                //    //if (!!_this.$refs.ImgIpt.focus) return;
                //    //判断焦点是否在输入框
                //    var input = document.getElementById("input");
                //    document.onkeydown = function (e) {
                //        //console.log(e) // 按下键盘上的 A 时会打印 a
                //        var keyCode = e.keyCode || e.which || e.charCode;
                //        var ctrlKey = e.ctrlKey || e.metaKey;
                //        console.log(keyCode, ctrlKey)
                //        if (ctrlKey && keyCode == 86) {
                //            if (input != document.activeElement && _this.showImgIpt) {
                //                hxt.error('请先点击输入框聚焦');
                //            };
                //        };
                //    };
                //},
                moveMedia: function (flag, row, index) {
                    var _this = this, mediaList = _this.mediaList;
                    console.log(row);
                    if (flag == 0) {
                        mediaList.splice(index, 1);
                        mediaList.splice(index - 1, 0, row);
                    }
                    else if (flag == 1) {
                        mediaList.splice(index, 1);
                        mediaList.splice(index + 1, 0, row);
                    }
                    else if (flag == 2) {//删除
                        //var url = ('' + row.miUrl).toLowerCase();
                        //if (!!url.startsWith('https://')) {
                        //    hxt.post({
                        //        url: hxt.config.link + 'pc/_ossDel',
                        //        data: { miId: row.miId, url: row.miUrl, flag:1 },
                        //        ok: function (res) {
                        //            if (res.code != 0) return hxt.error('删除失败：' + res.errmsg);
                        //            hxt.success('删除成功');
                        //            mediaList.splice(index, 1);
                        //        }
                        //    });
                        //    return;
                        //};
                        mediaList.splice(index, 1);
                    }
                },
                handlePaste: function (value) {
                    try {
                        var _this = this, file = value.clipboardData.files
                        if (file.length > 0) {
                            file = file[0]
                        } else {
                            file = value.clipboardData.items[0].getAsFile()
                        };
                        if (!file) {
                            hxt.error('粘贴内容非文件');
                            return;
                        };
                        var ext = file.name.toLowerCase().split('.').splice(-1).join('');
                        if (_this.getFileType(2, 2).indexOf(ext) < 0) return hxt.error('仅支持' + _this.getFileType(2, 3) + '扩展名的文件');
                        hxt.compressImg(file, 2000, function (id, raw64, base64) {
                            var len = base64.split(',')[1].split('=')[0].length;
                            _this.addMedia({ type: 2 }, { miType: 2, miUrl: base64, miSize: _this.getFileSize(len - (len / 8) * 2) });
                        });
                        _this.showImgIpt = false;
                        //document.onkeydown = '';
                    } catch (e) {
                        hxt.error('导入出错了：' + e);
                    };
                },
                ClipBoard: function (e) {
                    if (!e) return;
                    var _this = this;
                    _this.showImgIpt = true;
                    _this.$nextTick(function () {
                        _this.$refs.ImgIpt.focus();
                        //_this.keyDown();
                    });
                    return;
                    try {
                        //HTTPS
                        navigator.clipboard // 创建clipboard对象
                            .read() // 调用readText()方法
                            .then(function (clipboardItems) {
                                // 成功回调
                                //console.log(clipboardItems, "clipboardItems =========");
                                clipboardItems.forEach(function (clipboardItem) {
                                    //console.log(clipboardItem, "clipboardItem ========="); // clipboardItem是一个实例对象
                                    clipboardItem.types.forEach(function (type) {
                                        clipboardItem
                                            .getType(type) // 读取接收到的mine类型作为参数，返回该类型的数据
                                            .then(function (res) {
                                                if (res.type == "text/plain") return hxt.error('粘贴内容非文件');
                                                var file = new window.File([res], Math.floor(Math.random() * 2147483648).toString(36) + '.png', { type: type });
                                                var ext = file.name.toLowerCase().split('.').splice(-1).join('');
                                                if (e.type == 2) {
                                                    if (_this.getFileType(2, 2).indexOf(ext) < 0) return hxt.error('仅支持' + _this.getFileType(2, 3) + '扩展名的文件');
                                                    hxt.compressImg(file, 1200, function (id, raw64, base64) {
                                                        var len = base64.split(',')[1].split('=')[0].length;
                                                        _this.addMedia(e, { miType: 2, miUrl: base64, miSize: _this.getFileSize(len - (len / 8) * 2) });
                                                    });
                                                }
                                            })
                                            .catch(function (err) { return hxt.error('导入失败：' + err) });
                                    });
                                });
                                // clipText是从剪贴板读取到的内容（也就是要粘贴的内容）
                            })
                            .catch(function (err) { return hxt.error('导入失败：' + err + '，注意：此导入方式仅支持微信、QQ截图，或者网页、文件中复制的图片，不能导入文件夹中复制的图片文件') }); // 失败回调
                    } catch (e) {
                        if (!navigator.clipboard) return hxt.error('导入失败：浏览器不支持');
                        hxt.error('出错了：' + e);
                    };
                },
                addMedia: function (e, values) {
                    var _this = this, mediaList = _this.mediaList, _default = { miId: 0, miType: 0, miTitle: '', miSize: '', miUrl: '', miIndex: 0, miDuration: '', rawUrl: null }
                        , clone = function (data) { return JSON.parse(JSON.stringify(data)); };
                    e = e || {};
                    var o = null;
                    if (e.type == 1 || e.type == 5) {
                        o = $.extend(clone(_default), { miType: e.type });
                    }
                    else if (e.type == 2 || e.type == 3 || e.type == 4 || e.type == 7) {
                        o = $.extend(clone(_default), values);
                    }
                    if (!!o) {
                        if (!e.item) mediaList.push(o);
                        else mediaList.splice(e.index, 0, o);
                    }
                },
                getFileType: function (type, flag) {
                    if (flag == 1) return hxt.getFileMimeStr(type);
                    else if (flag == 2) return hxt.getFileExtList(type);
                    else return hxt.getFileExtStr(type);
                },
                getFileSize: function (size) {
                    return hxt.getFileSize(size);
                },
                getDuration: function (duration) {
                    return hxt.getDuration(duration);
                },
                getFileIco: function (name) {
                    return hxt.getFileIco(name);
                },
                selectFile: function (file, opt) {
                    var _this = this;
                    var ext = file.name.toLowerCase().split('.').splice(-1).join('');
                    if (opt.type == 2) {
                        if (_this.getFileType(2, 2).indexOf(ext) < 0) return hxt.error('仅支持' + _this.getFileType(2, 3) + '扩展名的文件');
                        hxt.compressImg(file, 1200, function (id, raw64, base64) {
                            var len = base64.split(',')[1].split('=')[0].length;
                            _this.addMedia(opt, { miType: 2, miUrl: base64, miSize: _this.getFileSize(len - (len / 8) * 2) });
                        });
                    }
                    else if (opt.type == 3) {
                        if (_this.getFileType(3, 2).indexOf(ext) < 0) return hxt.error('仅支持' + _this.getFileType(3, 3) + '扩展名的文件');
                        hxt.mask();
                        var audio = new Audio();
                        audio.onloadedmetadata = function (e) {
                            hxt.unmask();
                            _this.addMedia(opt, { miType: 3, miUrl: file, rawUrl: URL.createObjectURL(file), miDuration: _this.getDuration(audio.duration), miSize: _this.getFileSize(file.size), miTitle: file.name });
                        };
                        audio.onerror = function (e) {
                            hxt.unmask();
                            return hxt.error('音频文件无效');
                        };
                        audio.src = URL.createObjectURL(file);
                        audio.load();
                    }
                    else if (opt.type == 4) {
                        if (_this.getFileType(4, 2).indexOf(ext) < 0) return hxt.error('仅支持' + _this.getFileType(4, 3) + '扩展名的文件');
                        hxt.mask();
                        var audio = document.createElement('video');
                        audio.onloadedmetadata = function (e) {
                            hxt.unmask();
                            _this.addMedia(opt, { miType: 4, miUrl: file, rawUrl: URL.createObjectURL(file), miDuration: _this.getDuration(audio.duration), miSize: _this.getFileSize(file.size), miTitle: file.name });
                        };
                        audio.onerror = function (e) {
                            hxt.unmask();
                            return hxt.error('视频文件无效');
                        };
                        audio.src = URL.createObjectURL(file);
                        audio.load();
                    }
                    else if (opt.type == 7) {
                        if (_this.getFileType(7, 2).indexOf(ext) < 0) return hxt.error('仅支持' + _this.getFileType(7, 3) + '扩展名的文件');
                        _this.addMedia(opt, { miType: 7, miUrl: file, miSize: _this.getFileSize(file.size), miTitle: file.name });
                    }
                },
            },
            components: {
                fileCover: hxt.fileCover(),
            }
        };
    })(window.$jscript.fn);
</script>
<style>
</style>